﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SecurityApi.DataAccess
{
    public class EnterpriseRepository : BaseRepository
    {
        public int AddEnterprise(string enterpriseName)
        {
            int enterpriseId = -1;

            try
            {
                Enterprise enterprise = new Enterprise();
                enterprise.Name = enterpriseName;
                enterprise.adt_DateCreated = DateTime.Now;
                _context.Enterprises.Add(enterprise);
                _context.SaveChanges();
                enterpriseId = enterprise.EnterpriseId;
            }
            catch (Exception ex)
            {
                enterpriseId = -1;
            }

            return enterpriseId;
        }

        public bool RemoveEnterprise(string name)
        {
            bool bResult = true;

            try
            {
                Enterprise enterprise = _context.Enterprises.Where(p => p.Name == name).SingleOrDefault();
                if (null != enterprise)
                {
                    _context.Enterprises.Remove(enterprise);
                    _context.SaveChanges();
                }
                else
                {
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                bResult = false;
            }

            return bResult;
        }

        public SecurityApi.Model.Enterprise GetEnterpriseByName(string enterpriseName)
        {
            //Enterprise enterprise = _context.Enterprises.Where(p => p.Name == name).SingleOrDefault();
            //return enterprise;
            enterpriseName = enterpriseName.Trim();

            SecurityApi.Model.Enterprise enterprise = GetAllEnterprises().Where(p => p.Name == enterpriseName).SingleOrDefault();
            return enterprise;

        }

        public IQueryable<SecurityApi.Model.Enterprise> GetAllEnterprises()
        {
            var query = from e in _context.Enterprises
                        select new SecurityApi.Model.Enterprise { Active = e.Active, Id = e.EnterpriseId, Name = e.Name, Title = e.Title };
            return query;
        }

        public SecurityApi.Model.Enterprise GetEnterpriseById(int id)
        {
            SecurityApi.Model.Enterprise enterprise = GetAllEnterprises().Where(p => p.Id == id).SingleOrDefault();
            return enterprise;
        }

        public IQueryable<Enterprise> GetAll()
        {
            var query = from e in _context.Enterprises select e;
            return query;
        }
    }
}
